package com.dealer.management.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dealer.management.common.Result;
import com.dealer.management.entity.Supplier;
import com.dealer.management.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    @GetMapping("/page")
    public Result<IPage<Supplier>> getSupplierPage(@RequestParam(defaultValue = "1") Integer current,
                                                   @RequestParam(defaultValue = "10") Integer size,
                                                   @RequestParam(required = false) String name) {
        Page<Supplier> page = new Page<>(current, size);
        IPage<Supplier> supplierPage = supplierService.getSupplierPage(page, name);
        return Result.success(supplierPage);
    }

    @GetMapping("/{id}")
    public Result<Supplier> getSupplierById(@PathVariable Long id) {
        Supplier supplier = supplierService.getSupplierById(id);
        return supplier != null ? Result.success(supplier) : Result.error("供应商不存在");
    }

    @PostMapping
    public Result<Boolean> saveSupplier(@RequestBody Supplier supplier) {
        boolean result = supplierService.saveSupplier(supplier);
        return result ? Result.success(true) : Result.error("保存失败");
    }

    @PutMapping
    public Result<Boolean> updateSupplier(@RequestBody Supplier supplier) {
        boolean result = supplierService.updateSupplier(supplier);
        return result ? Result.success(true) : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteSupplier(@PathVariable Long id) {
        boolean result = supplierService.deleteSupplier(id);
        return result ? Result.success(true) : Result.error("删除失败");
    }
}
